package com.huarui.quotation.dao.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.ewaf.framework.dao.impl.BaseDaoImpl;
import org.ewaf.framework.exception.BizException;

import org.springframework.orm.ibatis.SqlMapClientCallback;

import com.huarui.area.dao.IAreaDao;
import com.huarui.area.model.Area;
import com.huarui.company.dao.ICompanyDao;
import com.huarui.company.model.Company;
import com.huarui.inventory.dao.IInventoryDao;
import com.huarui.market.dao.IMarketDao;
import com.huarui.market.model.Market;
import com.huarui.quotation.dao.IQuotationDao;
import com.huarui.quotation.error.ErrorCode;
import com.huarui.quotation.model.Quotation;
import com.ibatis.sqlmap.client.SqlMapExecutor;

public class QuotationDaoImpl extends BaseDaoImpl implements IQuotationDao {
	private IInventoryDao inventoryDao;
	private ICompanyDao companyDao;
	private IAreaDao areaDao;
	private IMarketDao marketDao;
	public void setInventoryDao(IInventoryDao inventoryDao) {
		this.inventoryDao = inventoryDao;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Map<String, String>> getQuotationsByCode(Integer source,
			String code) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("source", source);
		map.put("code", code);
		return this.getSqlMapClientTemplate().queryForList(
				super.namespace + ".getPartsByCode", map);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Map<String, String>> getQuotationsByName(Integer source,
			String name) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("source", source);
		map.put("name", name);
		return this.getSqlMapClientTemplate().queryForList(
				super.namespace + ".getPartsByCode", map);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Map<String, String>> getQuotationsByComplexCond(
			Map<String, String> map) {

		return this.getSqlMapClientTemplate().queryForList(
				super.namespace + ".getPartsByCode", map);
	}

	@SuppressWarnings("unused")
	private void putParams(Map<String, Object> map, String[] params) {
		if (params == null) {
			throw new BizException(ErrorCode.PARAMS_IS_NULL);
		}
		if (params.length != 10) {
			throw new BizException(ErrorCode.PARAMS_NUM_ERROR);
		}
		try {
			if (params[0] != null && !"".equals(((String) params[0]).trim())) {
				map.put("carModelId", Integer.parseInt(((String) params[0])
						.trim()));
			}
			if (params[1] != null && !"".equals(((String) params[1]).trim())) {
				map.put("level1Id", Integer.parseInt(((String) params[1])
						.trim()));
			}
			if (params[2] != null && !"".equals(((String) params[2]).trim())) {
				map.put("level2Id", Integer.parseInt(((String) params[2])
						.trim()));
			}
			if (params[3] != null && !"".equals(((String) params[3]).trim())) {
				map
						.put("source", Integer.parseInt(((String) params[3])
								.trim()));
			}
			if (params[4] != null && !"".equals(((String) params[4]).trim())) {
				map.put("code", ((String) params[4]).trim());
			}
			if (params[5] != null && !"".equals(((String) params[5]).trim())) {
				map.put("name", ((String) params[5]).trim());
			}
			if (params[6] != null && !"".equals(((String) params[6]).trim())) {
				map.put("swapCode", ((String) params[6]).trim());
			}
			if (params[7] != null && !"".equals(((String) params[7]).trim())) {
				map.put("brand", ((String) params[7]).trim());
			}
			if (params[8] != null && !"".equals(((String) params[8]).trim())) {
				map.put("origin", ((String) params[8]).trim());
			}
			if (params[9] != null && !"".equals(((String) params[9]).trim())) {
				map
						.put("onHand", Integer.parseInt(((String) params[9])
								.trim()));
			}
			// if (params[10] != null && ! "".equals(
			// ((String)params[10]).trim() ) ) {
			// map.put("", params[10]);
			// }
		} catch (RuntimeException re) {
			if (re instanceof ClassCastException) {
				throw new BizException(ErrorCode.PARAMS_TYPE_ERROR);
			} else if (re instanceof NumberFormatException) {
				throw new BizException(ErrorCode.PARAMS_TYPE_ERROR);
			} else {
				throw new BizException(ErrorCode.PARAMS_OTHER_ERROR);
			}
		}

	}

	@Override
	public Integer getQuotaCountInfo(Map<String, Object> map) {
		return (Integer) this.getSqlMapClientTemplate().queryForObject(
				super.namespace + ".getQuotaCountInfo", map);
	}

//	@Override
//	@SuppressWarnings("unchecked")
//	public List<Map<String, Object>> getQuotationListByComplex(Map<String, Object> map) {
//		return this.getSqlMapClientTemplate().queryForList(
//				super.namespace + ".getQuotaByComplex", map);
//	}

	@SuppressWarnings("unchecked")
	public Quotation getQuotationByInventoryId(Map map) {
		return (Quotation) getSqlMapClientTemplate().queryForObject(namespace + ".getQuotationByInventoryId", map);
	}

	/**
	 * 批量插入报价表
	 * 
	 * @param receiveItems
	 * @param companyId
	 * @param companyName
	 */
	@Override
	public void batchInsertQuotation(final List<Quotation> quotations) {
		getSqlMapClientTemplate().execute(new SqlMapClientCallback() {

			@Override
			public Object doInSqlMapClient(SqlMapExecutor executor)
					throws SQLException {
				executor.startBatch();
				int batch = 0;
				for (Quotation quotation : quotations) {
					executor.insert(namespace + ".create", quotation);
					batch++;
					if (batch == 300) {
						executor.executeBatch();
						batch = 0;
					}
				}
				executor.executeBatch();
				return null;
			}
		});

	}
	/**
	 * 批量删除报价表
	 * 
	 * @param receiveItems
	 * @param companyId
	 * @param companyName
	 */
	@Override
	public void batchDeleteQuotation(List<Quotation> quotations) {
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("partPropertyList", quotations);
		this.getSqlMapClientTemplate().delete(namespace+".deleteByCondition", map);
	}
	@Override
	public void bacthUpdatQuotation(final List<Quotation> quotations) {
		getSqlMapClientTemplate().execute(new SqlMapClientCallback() {

			@Override
			public Object doInSqlMapClient(SqlMapExecutor executor)
					throws SQLException {
				executor.startBatch();
				int batch = 0;
				for (Quotation quotation : quotations) {
					executor.update(namespace + ".update", quotation);
					batch++;
					if (batch == 100) {
						executor.executeBatch();
						batch = 0;
					}
				}
				executor.executeBatch();
				return null;
			}
		});

	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> searchQuotationByComplex(
			Map<String, Object> paramsMap) {
		return this.getSqlMapClientTemplate().queryForList(super.namespace + ".searchQuotationByComplex", paramsMap);
	}

	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> searchFirstPageQuotationByComplex(Map<String, Object> paramsMap) {
		return this.getSqlMapClientTemplate().queryForList(super.namespace + ".searchFirstPageQuotationByComplex", paramsMap);
	}
	
	@Override
	public Integer searchQuotationCountByComplex(Map<String, Object> paramsMap) {
		return (Integer) this.getSqlMapClientTemplate().queryForObject(super.namespace + ".searchQuotationCountByComplex", paramsMap);
	}

	@SuppressWarnings("unchecked")
	public boolean batchInsertQuotation(final List<Quotation> quotations,final Integer companyId){
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("companyId", companyId);
		Integer count=(Integer) this.getSqlMapClientTemplate().queryForObject(namespace+".validateInsertPermisstion",map);
		if(count>0){
			Company company = (Company) companyDao.getById(companyId);			
			Market market = (Market) marketDao.getMarketByCompanyId(company.getId());//modified by gongliang
			for(Quotation quotation:quotations){
				quotation.setMarketId(market.getId());
				quotation.setMarketName(market.getName());
				quotation.setProvinceId(company.getProvinceId());
				quotation.setProvince(company.getProvince());
				quotation.setCity(company.getCity());
				quotation.setRealType(company.getRealType());
				quotation.setCompanyType(company.getCompanyType());
				quotation.setCompanyId(company.getId());
				quotation.setCompanyName(company.getName());
			}
			batchInsertQuotation(quotations);
		}
		return count>0;
	}
	@SuppressWarnings("unchecked")
	public boolean createPassPermission(Quotation quotation,final Integer companyId){
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("companyId", companyId);
		Integer count=(Integer) this.getSqlMapClientTemplate().queryForObject(namespace+".validateInsertPermisstion",map);
		if(count>0){
			Company company = (Company) companyDao.getById(companyId);			
			Market market = (Market) marketDao.getMarketByCompanyId(company.getId());//modified by gongliang

				quotation.setMarketId(market.getId());
				quotation.setMarketName(market.getName());
				quotation.setProvinceId(company.getProvinceId());
				quotation.setProvince(company.getProvince());
				quotation.setRealType(company.getRealType());
				quotation.setCompanyType(company.getCompanyType());
				quotation.setCompanyId(company.getId());
				quotation.setCompanyName(company.getName());

			this.create(quotation);
		}
		return count>0;
	}
	@Override
	public void bacthUpdatQuotation(final List<Quotation> quotations,final Integer companyId) {
		if(validateInsertPermisstion(companyId))bacthUpdatQuotation(quotations);
	}
	public boolean validateInsertPermisstion(Integer companyId){
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("companyId", companyId);
		Integer count=(Integer) this.getSqlMapClientTemplate().queryForObject(namespace+".validateInsertPermisstion",map);
		return count>0;
	}
	public void setCompanyDao(ICompanyDao companyDao) {
		this.companyDao = companyDao;
	}

	public void setAreaDao(IAreaDao areaDao) {
		this.areaDao = areaDao;
	}

	public void setMarketDao(IMarketDao marketDao) {
		this.marketDao = marketDao;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Quotation> getListByConditions(Map<String, Object> map) {
		return this.getSqlMapClientTemplate().queryForList(namespace+".getListByConditions",map);
	}
	
}
